from BloodSpiderModel.DjangoResponseTool.response_dict import response_dict, get_first_error, get_page

import time

from BloodSpiderAPI import models

from django import forms

from BloodSpiderAPI.apis.user import utils as user_utils


# 用户表单
class UserForm(forms.ModelForm):
    class Meta:
        model = models.User
        fields = "__all__"

# 接收易接单提供的用户信息
def receive_user_info(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)

    
    user_id = request.POST.get('uid')

    if user_id:
        user = models.User.objects.filter(uid=user_id).first()
        if user:
            user_response = user_utils.utils_model_to_dict(user)
            user_response["set_info_js_path"] = request.current_host + "/static/js/login.js"
            return response_dict(message="用户信息获取成功", code=0, data=user_response)
    form = UserForm(request.POST.dict())
    if not form.is_valid():
        return response_dict(data=get_first_error(form), code=1, message="参数错误")
    try:
        user = form.save()
        response = user_utils.utils_model_to_dict(user)
        user_response["set_info_js_path"] = request.current_host + "/static/js/login.js"
        return response_dict(message="用户创建成功", code=0, data=response)
    except Exception as e:
        return response_dict(message=f"创建失败: {str(e)}", code=1)



# 查询用户信息
def query_user_info(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    user_id = request.POST.get('uid')
    print("user_id:::", user_id)
    if not user_id:
        return response_dict(message="缺少用户ID参数", code=1)
    try:
        user = models.User.objects.get(uid=user_id)
        response = user_utils.utils_model_to_dict(user)
        return response_dict(message="用户信息查询成功", code=0, data=response)
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)